﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using IS.fitframework;
using IS.tc3lib;
using GoogleMaps;
using System.Data;
using IS.Comm;
using System.IO;

namespace sdata
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class tc3data : IServiceTC3
    {

        public string HelloWorld(string mes)
        {
            return "Hello World " + mes;
        }
        public int insert(CLIENT_REPORTLOG_OBJ client_obj)
        {
            const double c_error = 0.00001;
            CommonLib comlib = new CommonLib();
            //extension information 
            //get car information based on deviceid
            CAR_BUS bus_car = new CAR_BUS();
            CAR_OBJ obj_car = bus_car.GetByKey(new fieldpara("DEVICEID", client_obj.DEVICEID));
            bus_car.CloseConnection();
            if (obj_car == null)
            {
                //incase can't get car, assign default car
                obj_car = new CAR_OBJ();
                obj_car.COMPANYCODE = "UNKNOW";
                
            }
            //get driver information
            DRIVER_BUS bus_dri = new DRIVER_BUS();
            DRIVER_OBJ obj_dri = bus_dri.GetByKey(new fieldpara("personid", client_obj.DRIVERID));
            bus_dri.CloseConnection();
            if (obj_dri == null)
            {
                obj_dri = new DRIVER_OBJ();
            }

//            return -1;

            //get address
            string addresss = "";
            GoogleObject bus_goo = new GoogleObject();
            try
            {
                //GoogleObject bus_goo = new GoogleObject();
                DataTable dt = bus_goo.LongitudeLatitudeToAddress(client_obj.LONGITUDE, client_obj.LATITUDE);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        addresss = comlib.string4Row(dt.Rows[0], "location", "");
                    }
                    dt.Dispose();
                }
            }
            catch (Exception ex)
            {
                //do nothing
            }
            int ret = 0;
            //updatet temp information
            REPORTTEMP_BUS bus_temp = new REPORTTEMP_BUS();
            REPORTTEMP_OBJ obj_temp = bus_temp.GetByKey(new fieldpara("COMPANYCODE", obj_car.COMPANYCODE), new fieldpara("DEVICEID", client_obj.DEVICEID));
            int isInsert=0;
            if (obj_temp == null)
            {
                isInsert=1;
                obj_temp = new REPORTTEMP_OBJ();
                obj_temp.CODE = bus_temp.GenNextCode(obj_temp);//assign new code for the first time
                obj_temp.LATITUDE = client_obj.LATITUDE;
                obj_temp.LONGITUDE = client_obj.LONGITUDE;
                obj_temp.REPORTTIME = client_obj.REPORTTIME;
            }
            //check in case the timer is not good
            if (client_obj.REPORTTIME < obj_temp.REPORTTIME)
            {
                return -1;//dont caculate
            }
            //check for the driver is the first time appearing in this car

            //summechanicdistance	float
            //sumstop	int
            //sumoverspeed	int
            //beginoverspeed	datetime
            //beginstop	datetime
            //begindriving	datetime

            //check for begin driving

            debug(1, "C:\\inetpub\\wwwroot\\logerror.txt", "object created");

//            if (client_obj.REPLAY == 1)
            {
                //the new frame
                if (obj_temp.DRIVERID != obj_dri.PERSONID)
                {
                    //start to count every thing base on driver
                    obj_temp.BEGINDRIVING = client_obj.REPORTTIME;
                }
                //Check for stop problem
                if (client_obj.MECHANICSPEED < c_error)//assume the error
                {
                    //stopping
                    if (obj_temp.BEGINSTOP == comlib.minDate())
                    {
                        //begin stopping
                        obj_temp.BEGINSTOP = client_obj.REPORTTIME;
                    }
                }
                else{
                    //running
                    if (obj_temp.BEGINSTOP != comlib.minDate())
                    {
                        //begin running (after stopping)
                        if (bus_temp.hasStopped(obj_temp.BEGINSTOP, obj_temp.REPORTTIME) > 0)
                        {
                            //has stopped
                            obj_temp.SUMSTOP++;//increase number of stopped
                        }
                        //in case full stop to reset begin driving
                        if (bus_temp.checkFullStop(obj_temp.BEGINSTOP, obj_temp.REPORTTIME) > 0)
                        {
                            obj_temp.BEGINDRIVING = client_obj.REPORTTIME;//reset begin driving
                        }
                        obj_temp.SUMDRIVING += bus_temp.getTimeperiod(obj_temp.REPORTTIME, client_obj.REPORTTIME);
                        obj_temp.BEGINSTOP = comlib.minDate();//running so that has not stopped
                    }
                }
                //check for sum distance
                if (obj_temp.MECHANICSPEED > c_error || client_obj.MECHANICSPEED > c_error)
                {
                    //running status
                    obj_temp.SUMMECHANICDISTANCE += bus_temp.getDistance(obj_temp.MECHANICSPEED, client_obj.MECHANICSPEED, obj_temp.REPORTTIME, client_obj.REPORTTIME);
                }
                //check the new day
                if (bus_temp.newDate(obj_temp.REPORTTIME, client_obj.REPORTTIME) == 1)
                {
                    //change to next day
                    obj_temp.SUMMECHANICDISTANCE = 0;//reset counter
                    obj_temp.SUMDRIVING = 0;//reset counter
                    obj_temp.SUMSTOP = 0;
                    obj_temp.SUMOVERSPEED = 0;
                }
                //sum over speed
                if (bus_temp.overSpeed(client_obj.MECHANICSPEED) == 1)
                {
                    //over speed
                    if (bus_temp.overSpeed(obj_temp.MECHANICSPEED) == 0)
                    {
                        //begin over speed
                        obj_temp.BEGINOVERSPEED = client_obj.REPORTTIME;
                    }

                }
                else
                {
                    //stop over speed
                    if (bus_temp.overSpeed(obj_temp.MECHANICSPEED) == 1 && obj_temp.BEGINOVERSPEED!=comlib.minDate())
                    {
                        //stop over speed
                        if (bus_temp.checkOverSpeed(obj_temp.BEGINOVERSPEED, obj_temp.REPORTTIME) == 1)
                        {
                            obj_temp.SUMOVERSPEED++;
                        }
                        obj_temp.BEGINOVERSPEED = comlib.minDate();

                    }
                }

            }
            //else
            //{
            //    //replay
            //}

            obj_temp.CAMERARELAY = client_obj.CAMERARELAY;
            obj_temp.CHECKER = client_obj.CHECKER;
            obj_temp.CODEVIEW = client_obj.CODEVIEW;
            obj_temp.COMPANYCODE = obj_car.COMPANYCODE;//client_obj.COMPANYCODE; get from car
            obj_temp.DATADELETE = client_obj.DATADELETE;
            obj_temp.DEVICEID = client_obj.DEVICEID;
            obj_temp.DRIVERID = client_obj.DRIVERID;
            obj_temp.EDITTIME = client_obj.EDITTIME;
            obj_temp.EDITUSER = client_obj.EDITUSER;
            obj_temp.ENDFARE = client_obj.ENDFARE;
            obj_temp.ENDFAREEVENT = client_obj.ENDFAREEVENT;
            obj_temp.ENGINEON = client_obj.ENGINEON;
            obj_temp.FARE = client_obj.FARE;
            obj_temp.FAREDISTANCE = client_obj.FAREDISTANCE;
            obj_temp.FUELLEVEL = client_obj.FUELLEVEL;
            obj_temp.FUELRELAY = client_obj.FUELRELAY;
            obj_temp.GPSSPEED = client_obj.GPSSPEED;
            obj_temp.INCAR = client_obj.INCAR;
            obj_temp.INFARE = client_obj.INFARE;
            obj_temp.INFARECAMERE = client_obj.INFARECAMERE;
//                obj_temp.LATITUDE = client_obj.LATITUDE;
            obj_temp.LOCK = client_obj.LOCK;
            obj_temp.LOCKDATE = client_obj.LOCKDATE;
//                obj_temp.LONGITUDE = client_obj.LONGITUDE;
            obj_temp.MECHANICDISTANCE = client_obj.MECHANICDISTANCE;
            obj_temp.MECHANICSPEED = client_obj.MECHANICSPEED;
            obj_temp.MEMORY = client_obj.MEMORY;
            obj_temp.NAME = client_obj.NAME;
            obj_temp.NOTE = client_obj.NOTE;
            obj_temp.OPENAIR = client_obj.OPENAIR;
            obj_temp.OPENDOOR = client_obj.OPENDOOR;
            obj_temp.OPENENGINE = client_obj.OPENENGINE;
            obj_temp.PICKUPTIME = client_obj.PICKUPTIME;
            obj_temp.POSITIONFIX = client_obj.POSITIONFIX;
            obj_temp.REPLAY = client_obj.REPLAY;
            obj_temp.SOS = client_obj.SOS;
            obj_temp.WAITINGFARE = client_obj.WAITINGFARE;
            obj_temp.WAITINGTIME = client_obj.WAITINGTIME;
            obj_temp.WASTEDISTANCE = client_obj.WASTEDISTANCE;
// description information
            obj_temp.DETAILADDRESS = addresss;
            obj_temp.CARNUMBER = obj_car.CODEVIEW;
            obj_temp.CARVIN = obj_car.VIN;
            obj_temp.DRIVERLICENCE = obj_dri.LICENCENUMBER;
            obj_temp.DRIVERNAME = obj_dri.NAME;
            obj_temp.DRIVERPHONE = obj_dri.PHONE;


            //assign for pre
            obj_temp.REPORTTIMEPRE = obj_temp.REPORTTIME;
            obj_temp.REPORTTIME = client_obj.REPORTTIME;

            obj_temp.LATITUDEPRE = obj_temp.LATITUDE;
            obj_temp.LATITUDE = client_obj.LATITUDE;

            obj_temp.LONGITUDEPRE = obj_temp.LONGITUDE;
            obj_temp.LONGITUDE = client_obj.LONGITUDE;



            if(isInsert==1)
            {
                ret = bus_temp.Insert(obj_temp);
            }
            else
            {
                //for update
                obj_temp._ID.CODE = obj_temp.CODE;
                ret = bus_temp.Update(obj_temp);
            }
            bus_temp.CloseConnection();

            //insert to reprotlog
            
            REPORTLOG_BUS bus = new REPORTLOG_BUS();
            REPORTLOG_OBJ obj = new REPORTLOG_OBJ();
            obj.CODE = bus.GenNextCode(obj);        
            obj.CAMERARELAY = client_obj.CAMERARELAY;
            obj.CHECKER = client_obj.CHECKER;
            obj.CODEVIEW = client_obj.CODEVIEW;
            obj.COMPANYCODE = client_obj.COMPANYCODE;
            obj.DATADELETE = client_obj.DATADELETE;
            obj.DEVICEID = client_obj.DEVICEID;
            obj.DRIVERID = client_obj.DRIVERID;
            obj.EDITTIME = client_obj.EDITTIME;
            obj.EDITUSER = client_obj.EDITUSER;
            obj.ENDFARE = client_obj.ENDFARE;
            obj.ENDFAREEVENT = client_obj.ENDFAREEVENT;
            obj.ENGINEON = client_obj.ENGINEON;
            obj.FARE = client_obj.FARE;
            obj.FAREDISTANCE = client_obj.FAREDISTANCE;
            obj.FUELLEVEL = client_obj.FUELLEVEL;
            obj.FUELRELAY = client_obj.FUELRELAY;
            obj.GPSSPEED = client_obj.GPSSPEED;
            obj.INCAR = client_obj.INCAR;
            obj.INFARE = client_obj.INFARE;
            obj.INFARECAMERE = client_obj.INFARECAMERE;
            obj.LATITUDE = client_obj.LATITUDE;
            obj.LOCK = client_obj.LOCK;
            obj.LOCKDATE = client_obj.LOCKDATE;
            obj.LONGITUDE = client_obj.LONGITUDE;
            obj.MECHANICDISTANCE = client_obj.MECHANICDISTANCE;
            obj.MECHANICSPEED = client_obj.MECHANICSPEED;
            obj.MEMORY = client_obj.MEMORY;
            obj.NAME = client_obj.NAME;
            obj.NOTE = client_obj.NOTE;
            obj.OPENAIR = client_obj.OPENAIR;
            obj.OPENDOOR = client_obj.OPENDOOR;
            obj.OPENENGINE = client_obj.OPENENGINE;
            obj.PICKUPTIME = client_obj.PICKUPTIME;
            obj.POSITIONFIX = client_obj.POSITIONFIX;
            obj.REPLAY = client_obj.REPLAY;
            obj.REPORTTIME = client_obj.REPORTTIME;
            obj.SOS = client_obj.SOS;
            obj.WAITINGFARE = client_obj.WAITINGFARE;
            obj.WAITINGTIME = client_obj.WAITINGTIME;
            obj.WASTEDISTANCE = client_obj.WASTEDISTANCE;
//addition information
            obj.DETAILADDRESS = addresss;
            obj.CARNUMBER = obj_car.CODEVIEW;
            obj.CARVIN = obj_car.VIN;
            obj.DRIVERLICENCE = obj_dri.LICENCENUMBER;
            obj.DRIVERNAME = obj_dri.NAME;
            obj.DRIVERPHONE = obj_dri.PHONE;
            //pre
            //for the pre
            obj.LONGITUDEPRE = obj_temp.LONGITUDEPRE;
            obj.LATITUDEPRE = obj_temp.LATITUDEPRE;
            obj.REPORTTIMEPRE = obj_temp.REPORTTIMEPRE;
            //copy from obj_temp
            obj.BEGINDRIVING = obj_temp.BEGINDRIVING;
            obj.BEGINSTOP = obj_temp.BEGINSTOP;
            obj.SUMSTOP = obj_temp.SUMSTOP;
            obj.SUMDRIVING = obj_temp.SUMDRIVING;
            obj.SUMMECHANICDISTANCE = obj_temp.SUMMECHANICDISTANCE;
            obj.BEGINOVERSPEED = obj_temp.BEGINOVERSPEED;
            obj.SUMOVERSPEED = obj_temp.SUMOVERSPEED;


            ret = 0;
            ret = bus.Insert(obj);
            bus.CloseConnection();

            return ret;
        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
        int debugMode = 2;
        public bool writeit(StreamWriter w, string content)
        {
            try
            {
                if (w != null)
                {
                    w.WriteLine("{0} - {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"), content);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public bool debug(string logfile, string content)//default 1
        {
            return debug(1, logfile, content);
        }
        public  bool debug(int level, string logfile, string content)//default 1
        {
            if (debugMode < level)
            {
                return false;//abort writing 
            }
            try
            {
                StreamWriter w = File.AppendText(logfile);
                writeit(w, content);
                w.Close();
                w.Dispose();
            }
            catch (Exception ex)
            {
                return false;
            }
            return false;
        }
    }
}
